package com.ruoyi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.StringUtils;
import com.ruoyi.constant.K_RandomUtil;
import com.ruoyi.entity.PrivilegeUser;
import com.ruoyi.mapper.PrivilegeUserMapper;
import com.ruoyi.service.AuthorityService;
import com.ruoyi.vo.PermissionApplyVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;

@Service
public class AuthorityServiceImpl implements AuthorityService {

    @Resource
    PrivilegeUserMapper privilegeUserMapper;


    @Override
    public Object permissionApply(PermissionApplyVo vo) {
        if(StringUtils.isEmpty(vo.getName())){
            return "请填写姓名";
        }
        if(StringUtils.isEmpty(vo.getPhone())){
            return "请填写手机号码";
        }
        //判断是否已经存在！
        QueryWrapper<PrivilegeUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",vo.getPhone());
        queryWrapper.eq("name",vo.getName());
        PrivilegeUser privilegeUserCheck = privilegeUserMapper.selectOne(queryWrapper);
        if(privilegeUserCheck!=null){
            return "该用户已经申请过权限了！";
        }
        //权限申请
        PrivilegeUser privilegeUser = new PrivilegeUser();
        privilegeUser.setName(vo.getName());
        privilegeUser.setPhone(vo.getPhone());
        String str1 = K_RandomUtil.generateAssignLengthRandomCode(6,3);
        String str2 = K_RandomUtil.generateAssignLengthRandomCode(6,3);
        String str3 = K_RandomUtil.generateAssignLengthRandomCode(6,3);
        String appKey = str1+"-"+str2+"-"+str3;
        String appId = K_RandomUtil.generateAssignLengthRandomCode(8,1);
        privilegeUser.setAppKey(appKey);
        privilegeUser.setAppId(appId);
        privilegeUserMapper.insert(privilegeUser);
        HashMap result = new HashMap();
        result.put("msg","权限申请成功，请保存以下信息。");
        result.put("APP-ID",appId);
        result.put("APP-KEY",appKey);
        return result;
    }
}
